<template>
  <base-page-view class-name="hot-buy-container">
    <template v-if="!pageLoading">
      <view v-if="crushId" class="sticky-wrap title-line">
        <view class="time">
          <view class="left">距结束</view>
          <view class="time-item">{{ remainingTimeHour }}</view> : <view class="time-item">{{ remainingTimeMinute }}</view> : <view class="time-item">{{ remainingTimeSecond }}</view>
        </view>
        <view v-if="nextStartTime > 0" class="next">{{ timeTitle }} {{ nextStartTime | formatDate(timeTitle ? 'HH:mm' : 'MM-dd HH:mm') }}</view>
      </view>
      <view class="list">
        <template v-for="(item, index) in list">
          <hotGoodsItem :key="index" :crush-id="crushId" :goods="item" :border="index!==list.length-1" />
        </template>
      </view>
      <base-list-state :list-length="listLength" :list-query="{ page_no: listQuery.pageNum, page_size: listQuery.pageSize }" :list-state="listState" :list-empty="listEmpty" />
    </template>
  </base-page-view>
</template>

<script>
import { mapState } from 'vuex'
import { debounce } from '@/utils/tools'
import hotGoodsItem from '@/components/hotGoodsItem/index'
import './index.scss'
export default {
  components: {
    hotGoodsItem
  },
  data() {
    return {
      pageLoading: true,
      hotTimer: null,
      crushId: '',
      remainingTime: '',
      remainingTimeDay: 0,
      remainingTimeHour: '',
      remainingTimeMinute: '',
      remainingTimeSecond: '',
      nextStartTime: 0,
      timeTitle: '',
      listQuery: {
        pageNum: 1,
        pageSize: 10
      },
      list: [],
      listState: {
        loading: false,
        more: true
      },
      listEmpty: {
        type: 'empty_network',
        text: '暂无数据哦~~'
      }
    }
  },
  computed: {
    ...mapState([
      'token',
      'userInfo'
    ]),
    listLength() { // 由于微信小程序无法自动更新base-list-state组件,故采用computed
      return this.list.length
    }
  },
  onLoad(option) {
    if (this.userInfo && this.userInfo.uid) {
      this.listQuery.userId = this.userInfo.uid
    }
  },
  onShow() {
    this.listQuery.pageNum = 1
    this.fetchData(true)
  },
  onPullDownRefresh() {
    this.listQuery.pageNum = 1
    this.fetchData(true)
  },
  onReachBottom: debounce(function() {
    if (this.listState.more && !this.listState.loading) {
      this.listQuery.pageNum++
      this.fetchData()
    }
  }, 500),
  methods: {
    async fetchData(flag) {
      this.refreshFlag = !!flag
      this.listState.loading = true
      const res = await this.$api.homeApi.getHotBuy({ ...this.listQuery })
      if (this.listQuery.pageNum === 1) {
        this.list = []
      }
      if (res.success && res.data) {
        const { crushId, remainingTime, nextStartTime, bestSellerRespDTOs } = res.data
        this.crushId = crushId
        this.remainingTime = Number(remainingTime)
        this.nextStartTime = Number(nextStartTime)
        this.list = this.list.concat(bestSellerRespDTOs)
        this.listState.more = bestSellerRespDTOs.length === this.listQuery.pageSize
        this.initTimeTitle()
        this.formatHotTime()
        if (this.remainingTime > 0) {
          clearInterval(this.hotTimer)
          this.hotTimer = setInterval(() => {
            this.remainingTime -= 1
            this.formatHotTime()
            if (this.remainingTime < 0) {
              clearInterval(this.hotTimer)
              this.listQuery.pageNum = 1
              this.fetchData()
            }
          }, 1000)
          this.$on('hook:deactivated', () => {
            clearInterval(this.hotTimer);                                    
          })
        }
      }
      this.pageLoading = false

      setTimeout(() => {
        uni.stopPullDownRefresh()
        this.refreshFlag = false
        this.listState.loading = false
      }, 500)
    },
    formatHotTime() {
      let s = this.remainingTime
      const days = Math.floor(s / (60 * 60 * 24))
      this.remainingTimeDay = days
      s = s % (60 * 60 * 24)
      const hours = days * 24 + Math.floor(s / (60 * 60))
      this.remainingTimeHour = hours > 9 ? hours : ('0' + hours)
      s = s % (60 * 60)
      const minute = Math.floor(s / 60)
      this.remainingTimeMinute = minute > 9 ? minute : ('0' + minute)
      const second = s % 60
      this.remainingTimeSecond = second > 9 ? second : ('0' + second)
    },
    initTimeTitle() {
      const todayLastTime = (new Date()).setHours(23, 59, 59, 999)
      const tomorrowLastTime = todayLastTime + 24 * 60 * 60 * 1000
      if (this.nextStartTime > tomorrowLastTime) {
        this.timeTitle = ''
      } else if (this.nextStartTime > todayLastTime) {
        this.timeTitle = '明日 '
      } else {
        this.timeTitle = '今日 '
      }
    }
  }
}
</script>
